package com.learn.core.controller.manager;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LCourseSort;
import com.learn.core.domain.LCourseware;
import com.learn.core.domain.LCoursewareType;
import com.learn.core.dto.LCourseSortDTO;
import com.learn.core.service.ILCourseSortService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auther CodeGenerator
 * @create 2021-03-13 19:40:17
 * @describe 课程分类表前端控制器
 */
@Api("课程分类")
@RestController
@RequestMapping("/manager/csort")
public class LCourseSortController extends WebController<LCourseSort> {

    @Autowired
    private ILCourseSortService iLCourseSortService;

    //课程分类树
    @ApiOperation(value = "课程分类树")
    @UserLoginToken
    @PostMapping("/tree")
    public CommonResult<Object> tree(){
        try {
            List<LCourseSort> lCourseSorts = iLCourseSortService.queryLCourseSortAll();
            if(lCourseSorts.size()>0)
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS,lCourseSorts);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LCourseSort> list(@RequestBody LCourseSortDTO lCourseSortDTO){
        try {
            if(lCourseSortDTO==null){
                return new PageResult<LCourseSort>(null, null, ResultEnum.ERROR);
            }
            if(lCourseSortDTO.getPage()==null||lCourseSortDTO.getRows()==null){
                return new PageResult<LCourseSort>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCourseSortDTO.getPage(),lCourseSortDTO.getRows());
            QueryWrapper<LCourseSort> queryWrapper = new QueryWrapper<LCourseSort>();
            if(lCourseSortDTO.getCourseSortId()!=null)
                queryWrapper.eq("parent_node",lCourseSortDTO.getCourseSortId());
            else {
                queryWrapper.eq("parent_node",0);
            }
            Page<LCourseSort> lCourseSorts = (Page<LCourseSort>) iLCourseSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCourseSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCourseSorts.getTotal(), lCourseSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加课程分类", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LCourseSort lCourseSort, HttpServletRequest request){
        // token
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lCourseSort!=null) {
                if (StringUtils.isEmpty(lCourseSort.getCourseSortName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_COURSEWARE_NAME);
                }
                if (StringUtils.isEmpty(lCourseSort.getParentNode())) {
                    lCourseSort.setParentNode(0);
                }

                String CourseSortCode = CnToSpell.getPinYinHeadChar(lCourseSort.getCourseSortName());
                lCourseSort.setCourseSortCode(CourseSortCode);
                lCourseSort.setCreateTime(new Date());
                lCourseSort.setCreateUser(userId);
                if (iLCourseSortService.save(lCourseSort)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除课程分类", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LCourseSort lCourseSort){
        try {
            if(lCourseSort!=null){
                if(lCourseSort.getCourseSortId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lCourseSort.getCourseSortId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LCourseSort> queryWrapper = new QueryWrapper<LCourseSort>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LCourseSort> lCourseSorts = iLCourseSortService.list(queryWrapper);
            for (int j = 0; j < lCourseSorts.size(); j++) {
                LCourseSort lCourseSort = lCourseSorts.get(j);
                ids.add(lCourseSort.getCourseSortId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LCourseSort>();
        queryWrapper.in(true, "course_sort_id", ids);
        iLCourseSortService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新课程分类", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LCourseSort lCourseSort, HttpServletRequest request) {
        if(lCourseSort!=null){
            // token
            String token = request.getHeader("token");
            String userId = JwtUtil.getUserId(token);
            lCourseSort.setUpdateTime(new Date());
            lCourseSort.setUpdateUser(userId);
            if(iLCourseSortService.updateById(lCourseSort)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}

